package mobi.hami.huapin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import mobi.hami.huapin.base.Result;
import mobi.hami.huapin.dao.UserNoteLogMapper;
import mobi.hami.huapin.dao.UserNoteMapper;
import mobi.hami.huapin.dto.UserNoteDTO;
import mobi.hami.huapin.dto.UserNoteLogDTO;
import mobi.hami.huapin.model.*;
import mobi.hami.huapin.service.*;
import mobi.hami.huapin.util.BeanUtil;
import mobi.hami.huapin.util.Dates;
import mobi.hami.huapin.util.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;

/**
 * Create by 小峰 on 2018/9/13.
 * 用户贴条记录
 */
@Service
public class UserNoteLogServiceImpl implements UserNoteLogService {

    private static final Logger logger = LoggerFactory.getLogger(UserNoteLogServiceImpl.class);

    @Autowired
    private UserNoteLogMapper userNoteLogMapper;
    @Autowired
    private UserWechatService userWechatService;
    @Autowired
    private NoteScheduleService noteScheduleService;
    @Autowired
    private UserShareLogService userShareLogService;
    @Autowired
    private NoteInfoService noteInfoService;
    @Autowired
    private UserVisitLogService userVisitLogService;
    @Autowired
    private ThumbupLogService thumbupLogService;
    @Autowired
    private UserNoteMapper userNoteMapper;
    @Autowired
    private UserOrderService userOrderService;


    /**
     * 根据空间Id获取当天被贴条的信息
     *
     * @param spaceId
     * @return
     */
    @Override
    //@Cacheable(value = "UserNoteLog",key = "'getCurrentDayUserBySpicId'+#spaceid")
    public List<UserNoteLog> getCurrentDayUserBySpaceId(Integer spaceId) {
        return userNoteLogMapper.getCurrentDayUserBySpaceId(spaceId);

    }

    /**
     * 根据空间Id获取昨天新增的被系统的贴条信息
     *
     * @param spaceId
     * @return
     */
    public List<UserNoteLog> getYesterdayNewUserBySpaceId(Integer spaceId) {
        return userNoteLogMapper.getYesterdayNewUserBySpaceId(spaceId);
    }

    /**
     * 获取当前空间下其它用户及被贴条数（List）
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public List<UserNoteDTO> getUserNoteBySpaceIdAndUserId(Integer spaceId, Integer userId) {
        List<UserNoteDTO> userNoteDTOS = userNoteLogMapper.getUserNoteBySpaceIdAndUserId(spaceId, userId);
        userNoteDTOS.forEach(m -> {
            UserWechat userWechat = userWechatService.findModelbyUserId(m.getUser_id());
            if (userWechat != null && userWechat.getId() > 0) {
                m.setUser_head(userWechat.getHead_photo());
                m.setUser_name(userWechat.getNick_name());
            }
        });
        userNoteDTOS.sort(Comparator.comparing(UserNoteDTO::getNote_count));
        Collections.reverse(userNoteDTOS);
        return userNoteDTOS;
    }

    /**
     * 获取当前用户被贴的纸条数
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public Integer getUserNoteLogCount(Integer spaceId, Integer userId) {
        Integer values = userNoteLogMapper.getUserNoteLogCount(spaceId, userId);
        return values == null ? 0 : values;
    }


    /**
     * 获取当前用户当前时间贴出的纸条被回复的个数
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public Integer getUserReplyCount(Integer spaceId, Integer userId) {
        return userNoteLogMapper.getUserReplyCount(spaceId, userId);
    }

    /**
     * 获取7天被贴的纸条及当前被贴的纸条数
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public Map<String, Object> getUserByNote(Integer spaceId, Integer userId) {
        List<UserNoteLog> userNoteLogList = userNoteLogMapper.getUserByNote(spaceId, userId);
        int sevenSize = 0;
        Long currentSize = 0L;
        if (userNoteLogList != null && userNoteLogList.size() > 0) {
            sevenSize = userNoteLogList.size();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date zero = calendar.getTime();
            currentSize = userNoteLogList.stream().filter(m -> m.getCreate_time().after(zero)).count();
        }
        Map<String, Object> mapArr = new HashMap<>();
        mapArr.put("SevenSize", sevenSize);
        mapArr.put("CurrentSize", currentSize);
        return mapArr;

    }

    public Integer insertList(List<UserNoteLogDTO> userNoteLogList) {
        return userNoteLogMapper.insertListDTO(userNoteLogList);
    }


    /**
     * 查询被贴条List
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public List<UserNoteLogDTO> findListByToUserId(Integer spaceId, Integer userId) {
        return userNoteLogMapper.findListByToUserId(spaceId, userId);
    }


    /**
     * 查询被贴条List(包含是否点赞)
     *
     * @param spaceId
     * @param searchUserId
     * @param currentUserId
     * @return
     */
    public List<UserNoteLogDTO> findListThumbupByUserId(Integer spaceId, Integer searchUserId, Integer currentUserId) {
        return userNoteLogMapper.findListThumbupByUserId(spaceId, searchUserId, currentUserId);
    }

    /**
     * 获取补贴纸条信息(分页)
     *
     * @param map
     * @return
     */
    public Map<String, Object> getUserNoteLogByPage(Map<String, Object> map) {

        Integer shareId = 0;
        Integer searchUserId = 0;
        Integer currentUserId = 0;
        Integer spaceId = 0;
        Integer pageIndex = 1;
        Integer pageSize = 10;
        Page page = null;

        if (null != map && !map.isEmpty()) {
            shareId = map.get("shareId") == null ? 0 : Integer.parseInt(map.get("shareId").toString());
            searchUserId = map.get("searchUserId") == null ? 0 : Integer.parseInt(map.get("searchUserId").toString());
            currentUserId = map.get("currentUserId") == null ? 0 : Integer.parseInt(map.get("currentUserId").toString());
            spaceId = map.get("spaceId") == null ? 0 : Integer.parseInt(map.get("spaceId").toString());
            pageIndex = map.get("pageIndex") == null ? 1 : Integer.parseInt(map.get("pageIndex").toString());
            pageIndex = pageIndex == 0 ? 1 : pageIndex;
            pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
            pageSize = pageSize == 0 ? 10 : pageSize;
        }
        List<UserNoteLogDTO> userNoteLogList = null;
        if(userOrderService.findCountByuserIdAndAddressid(currentUserId,spaceId)<=0){
            pageSize=3;
            pageIndex=1;
        }
        if (searchUserId.equals(currentUserId)) {
            userNoteLogList = newUserNoteLogInfo(shareId, searchUserId, spaceId);
            if (userNoteLogList == null || userNoteLogList.size() <= 0) {
                page = PageHelper.startPage(pageIndex, pageSize, true).reasonable(true);
                userNoteLogList = findListByToUserId(spaceId, searchUserId);
            }
        } else {
            page = PageHelper.startPage(pageIndex, pageSize, true).reasonable(true);
            userNoteLogList = findListThumbupByUserId(spaceId, searchUserId, currentUserId);
        }
        saveUserVisitLog(currentUserId, searchUserId, spaceId);
        return BeanUtil.ResultResponseMap(page, userNoteLogList, pageSize, pageIndex);
    }


    private List<UserNoteLogDTO> newUserNoteLogInfo(Integer shareId, Integer userId, Integer spaceId) {
        UserNoteLog userNoteLog = new UserNoteLog();
        userNoteLog.setTo_user_id(userId);
        userNoteLog.setSpace_id(spaceId);
        Integer noteLogCount = userNoteLogMapper.selectCount(userNoteLog);
        List<UserNoteLogDTO> userNoteLogs = new ArrayList<>();
        //没有纸条数,新用户
        if (noteLogCount <= 0) {
            List<NoteSchedule> noteSchedules = noteScheduleService.FindRandLimitThree();
            UserShareLog userShareLog = null;
            if (shareId > 0) {
                userShareLog = userShareLogService.FindOneByPrimaryKey(shareId);
                if (userShareLog.getGuide_num() <= 0) {
                    NoteInfo noteInfo = noteInfoService.FindOneByPrimaryKey(userShareLog.getNote_id());
                    noteSchedules.get(0).setNote_id(noteInfo.getId());
                    noteSchedules.get(0).setContent(noteInfo.getComtent());
                }
            }
            for (NoteSchedule noteSchedule : noteSchedules) {
                UserNoteLogDTO userNoteLog1 = new UserNoteLogDTO();

                userNoteLog1.setSpace_id(spaceId);
                userNoteLog1.setTo_user_id(userId);
                userNoteLog1.setFrom_user_id(0);
                userNoteLog1.setCreate_time(new Date());
                userNoteLog1.setNote_comtent(noteSchedule.getContent());
                userNoteLog1.setNote_id(noteSchedule.getNote_id());
                userNoteLog1.setIs_reply(1);
                userNoteLogs.add(userNoteLog1);
            }
            if (insertList(userNoteLogs) > 0) {
                if (userShareLog != null) {
                    userShareLog.setGuide_num(userShareLog.getGuide_num() + 1);
                    userShareLogService.updateModel(userShareLog);
                }
            }
        }
        return userNoteLogs;
    }


    private Integer saveUserVisitLog(Integer fromVisitUser, Integer toVisitUser, Integer spaceId) {
        UserVisitLog userVisitLog = new UserVisitLog();
        userVisitLog.setCreate_time(new Date());
        userVisitLog.setFrom_visit_user(fromVisitUser);
        userVisitLog.setSpace_id(spaceId);
        userVisitLog.setTo_visit_user(toVisitUser);
        return userVisitLogService.InsertModel(userVisitLog);
    }

    /**
     * 获取当前用户被贴回复
     * 被贴者未回复过任何纸条情况下，显示回复率80%，一旦回复过任意纸条，该用户此状态下显示回复率90%，回复大于等于两张以上显示98%；
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getUserReplyRat(Integer userId) {

        int replycount = userNoteLogMapper.getUserAllReplyCount(userId);

        int rat = 80;
        if (replycount > 0) {
            replycount = 90;
            if (replycount > 2) {
                replycount = 98;
            }
        }

        return rat;
    }

    /**
     * 根据查询条件获取最新的被贴信息
     *
     * @param userId
     * @param spaceId
     * @return
     */
    public UserNoteLogDTO findModelByModel(Integer userId, Integer spaceId) {
        return userNoteLogMapper.findModelByModel(userId, spaceId);
    }

    /**
     * 更新用户回复的状态
     *
     * @param id
     * @param replyStatus
     * @return
     */
    public Integer updateUserNoteLogReply(Integer id, Integer replyStatus) {
        return userNoteLogMapper.updateUserNoteLogReply(id, replyStatus);
    }

    /**
     * 获取被贴出的纸条,回复列表
     *
     * @param mapRequest
     * @return
     */
    public Map<String, Object> getReplyUserNoteLogList(Map<String, Object> mapRequest) {

        Integer userId = 0;
        Integer spaceId = 0;
        Integer pageIndex = 0;
        Integer pageSize = 0;

        if (null != mapRequest && !mapRequest.isEmpty()) {
            userId = mapRequest.get("userId") == null ? 1 : Integer.parseInt(mapRequest.get("userId").toString());
            spaceId = mapRequest.get("spaceId") == null ? 1 : Integer.parseInt(mapRequest.get("spaceId").toString());
            pageIndex = mapRequest.get("pageIndex") == null ? 1 : Integer.parseInt(mapRequest.get("pageIndex").toString());
            pageIndex = pageIndex == 0 ? 1 : pageIndex;
            pageSize = mapRequest.get("pageSize") == null ? 10 : Integer.parseInt(mapRequest.get("pageSize").toString());
            pageSize = pageSize == 0 ? 10 : pageSize;
        }
        Page page = PageHelper.startPage(pageIndex, pageSize, true).reasonable(true);
        List<UserNoteLogDTO> userNoteLogList = userNoteLogMapper.getReplyUserNoteLogList(spaceId, userId);

        UserVisitLog userVisitLog = new UserVisitLog();
        userVisitLog.setTo_visit_user(0);
        userVisitLog.setSpace_id(spaceId);
        userVisitLog.setFrom_visit_user(userId);
        userVisitLog.setCreate_time(new Date());
        userVisitLogService.InsertModel(userVisitLog);
        return BeanUtil.ResultResponseMap(page, userNoteLogList, pageSize, pageIndex);
    }


    /**
     * 获取当前被贴纸条的个数
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public Integer getCurrentDayNoteLogSum(Integer spaceId, Integer userId) {
        return userNoteLogMapper.getCurrentDayNoteLogSum(spaceId, userId);
    }


    public Result getNoetStatus(Map<String, String> reqmap) {
        //判断用户是否有纸条
        int usernoteid = queryUsableUserNoteID(Integer.parseInt(reqmap.get("spaceid")), Integer.parseInt(reqmap.get("from_user_id")));
        if (usernoteid == 0) {
            return Results.failureWithStatus(110, "你已经没有可用纸条了");
        }

        //1,返回用户最近3天给，touserid的记录
        List<UserNoteLog> logList = userNoteLogMapper.queryUserGiveList(Integer.parseInt(reqmap.get("to_user_id")), Integer.parseInt(reqmap.get("from_user_id")));

        Calendar calendar = Calendar.getInstance();

        Date today = Dates.parseDate(Dates.format(calendar.getTime(), Dates.Pattern.DATE));

        logger.info("今天的时间：" + Dates.format(today, Dates.Pattern.DATE));

        for (int i = 0; i < logList.size(); i++) {
            if (logList.get(i).getCreate_time().getTime() == today.getTime()) {
                return Results.failureWithStatus(100, "贴过啦同一个人每天可贴1次");
            }
        }

        if (logList.size() >= 3) {
            //判断是否是连续了3天了，
            return Results.failureWithStatus(102, "为了避免骚扰，暂时不支持连续4天帖同一个人");
        }
        return Results.success();
    }
    /**
     * 给用户帖条
     *
     * @param reqmap
     * @return
     */
    @Override
    public Result giveUserNote(Map<String, String> reqmap) {

        //判断用户是否有纸条
        int usernoteid = queryUsableUserNoteID(Integer.parseInt(reqmap.get("spaceid")), Integer.parseInt(reqmap.get("from_user_id")));
        if (usernoteid == 0) {
            return Results.failureWithStatus(110, "你已经没有可用纸条了");
        }

        //1,返回用户最近3天给，touserid的记录
        List<UserNoteLog> logList = userNoteLogMapper.queryUserGiveList(Integer.parseInt(reqmap.get("to_user_id")), Integer.parseInt(reqmap.get("from_user_id")));

        Calendar calendar = Calendar.getInstance();

        Date today = Dates.parseDate(Dates.format(calendar.getTime(), Dates.Pattern.DATE));

        logger.info("今天的时间：" + Dates.format(today, Dates.Pattern.DATE));

        for (int i = 0; i < logList.size(); i++) {
            if (logList.get(i).getCreate_time().getTime() == today.getTime()) {
                return Results.failureWithStatus(100, "贴过啦同一个人每天可贴1次");
            }
        }

        if (logList.size() >= 3) {
            //判断是否是连续了3天了，
            return Results.failureWithStatus(102, "为了避免骚扰，暂时不支持连续4天帖同一个人");
        }

        UserNoteLog userNoteLog = new UserNoteLog();
        userNoteLog.setSpace_id(Integer.parseInt(reqmap.get("spaceid")));
        userNoteLog.setTo_user_id(Integer.parseInt(reqmap.get("to_user_id")));
        userNoteLog.setFrom_user_id(Integer.parseInt(reqmap.get("from_user_id")));
        userNoteLog.setNote_id(Integer.parseInt(reqmap.get("note_id")));
        userNoteLog.setNote_comtent(reqmap.get("note_comtent"));
        userNoteLog.setCreate_time(new Date());
        userNoteLog.setIs_reply(0);

        int rs = userNoteLogMapper.insertSelective(userNoteLog);

        if (rs > 0) {
            //更新用户的纸条状态
            userNoteMapper.usetUserNote(usernoteid);

            //判断 这个是不是第三个。
            calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -2);


            Date pre2day = Dates.parseDate(Dates.format(calendar.getTime(), Dates.Pattern.DATE));

            logger.info("今天（减2的）的时间：" + Dates.format(pre2day, Dates.Pattern.DATE));

            int notecount = 0;

            for (int i = 0; i < logList.size(); i++) {
                if (logList.get(i).getCreate_time().getTime() >= pre2day.getTime()) {
                    notecount++;
                }
            }

            if (notecount >= 2) {
                return Results.successWithStatus(1, "你已经连续3天，帖了同一个人");
            } else {
                return Results.successWithStatus(0, "");
            }


        } else {
            return Results.failureWithStatus(0, "服务器繁忙，请稍后再试");
        }

        //2,同一个人，最多连续3天，
    }


    /**
     * 获取用户最早的一条可能用的纸条的ID
     *
     * @param spaceId
     * @param userId
     * @return
     */
    public Integer queryUsableUserNoteID(Integer spaceId, Integer userId) {

        UserNoteExample example = new UserNoteExample();
        UserNoteExample.Criteria criteria = example.createCriteria();

        criteria.andStatusEqualTo(0);
        criteria.andSpace_idEqualTo(spaceId);
        criteria.andUser_idEqualTo(userId);
        example.setOrderByClause("type desc,id desc"); //先用每天赠送的

        PageHelper.startPage(1, 1);
        List<UserNote> userNotes = userNoteMapper.selectByExample(example);

        if (userNotes.size() > 0) {
            return userNotes.get(0).getId();
        } else {
            return 0;
        }
    }


    /**
     * 增加点赞次数
     *
     * @param spaceId
     * @param userId
     * @param noteLogId
     * @return
     */
    public Integer addThubupCountById(Integer spaceId, Integer userId, Integer noteLogId) {

        ThumbupLog thumbupLog = new ThumbupLog();
        thumbupLog.setCreate_time(new Date());
        thumbupLog.setCreate_user_id(userId);
        thumbupLog.setNote_long_id(noteLogId);
        thumbupLogService.saveThumbupLogByModel(thumbupLog);
        return userNoteLogMapper.addThubupCountById(noteLogId);
    }


    /**
     * 获取该空间下最近7天内的用户的气泡数前5的信息
     *
     * @param spaceId
     * @return
     */
    public List<UserNoteDTO> getUserNoteLogSevenDayCountBySpaceId(Integer spaceId) {
        return userNoteLogMapper.getUserNoteLogSevenDayCountBySpaceId(spaceId);
    }

    /**
     * 获取该空间下最新的被贴的纸条信息
     *
     * @param spaceId
     * @return
     */
    public List<Map> getLastNewFiveNoteLogBySpaceId(Integer spaceId) {
        return userNoteLogMapper.getLastNewFiveNoteLogBySpaceId(spaceId);
    }
}
